﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.Crmf;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using NanTongPost.Model;

namespace NanTongPost
{
    public class PostTool
    {
        public string url { get; set; } = "http://test.tztjt.com/open_platform_provider/open/api/exchange";
        public string appid { get; set; } = "sh20240910001";

        public string privateKey { get; set; } = "MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDD6g3FbQTMsZqjMtwIBlNlc5eL5n6y8ni9DLyNjPlhmY9Ri0JVEjftHZFJ0/hbnBShA/CckOvTwOkwzuDup771KnojDfaiXsxiPOT9cgRildMDM3zp85h3T9H+uQZUr5KJjJFouB4MlOBpvflAukGNsfauoBvqO0nZfT2Mrg5pmIvYsO+OKHNnTEn+aFtZKYX+t4ibQvU+0ZF2KZ0z34M88OisbfIV0WL8eWeUklR/tSsoe3U2jWJvYDnM0OwpMVAeNgJaaGTSFoLqsyfw2MxB5W9VZOEX7wApUNyvMk9q/ILpoDx57ps8MKL9q2xYrkGPcRuqlSxWSgaWwBot65zjAgMBAAECggEBAIMyimZby4sIpPYFaTQ2iEK4VhRqFw7fMdvoW5yve5HQtBl3mMQ/nxQ7aMB4Iym2LFpnuQogQs1bss3svNUVoNutxn0TLMcvlM902CSh5i3fB6BtKonBh6je21IptgOgUBGtAPOP2Q+z41Ts0651DNFHDFuE/Syu55WuOTmslho/0AYAG9YXFliakTJAyi4mEeQsYSz6+yGpmxE8QQrHAJv3urE6Y02TsT8Wvhw/b+Ttfto0qRD83tf5riiV4No3o+HpBf/nhBb/f2IOQ0E34VM8gENBkf354KnjT0UZtyo6x7L5xKDNAOEWX9Exg3NsS4pap86+QW6fZZDiqGB074ECgYEA+tVJbsTuH3jLmAXfu+4zR/FFmBVxJn8A0lcnTbmYoC3nrXB18DOkqevVraatZLcVV2NYEKXuAl1Tq7XRbP98RWRa8+a7FkWMg0I3oCj+kv2s99HuZh3+yezi+4aOl39j6+WEnQQGqbIbDrECbjXUIUz2UoMomcP4WE0esgcDe38CgYEAx/MqFQyAKIkkhdhS4uaG/p9rv6hHujyRZUahg/sF9Q3GLsTyAgYQuzIBKhe4QTvmdG/Qxy4gWzBspcg0i6sasAxgSIsd7lYDqWnfdEcuTD2bX+cgfoaD3Y1SYzWnMYEYz929yI6JBMa0mxF7a9yTwywjUwnlnlliRNMmEN8nIJ0CgYEAoxNn2oxOBEgUlZG8FAKZdHx4Mpg+KDkJ37ap5u5zPDCcHzaudqwcshyRn4Rt1rzxMw9zgd9fDkp+y3Q55BN2R+cm+stXdvNglzXF1GrSl941RilGRT3bGIzaRY0Fx5ka7ZMa1Lp5Wnpg/Pw4CE8Wy0+uFZcQHmg6Xa5F9ph4uyECgYEApOHdcuwTBtpItuKzPw6whWm7NZm0RFxL3YMID8jBmdmY8tpPYuHTjDppAWf79jdKC/xk4ssjvW7KOU9GHWKkqEYcY9XsgayGan622LEV+aLX7JawkgWk2d7+8Ha+/7CgYFFPfgIj9T9SkYkyCLklVE2id4hyxEibI3wnKMSMBHUCgYEAkwGy+9yR5MttaH+0R1FzprNupC2fv3OdxH8+RfYwL/J+huNHv6dkc1QSZloNeBeFxkvXIsVocJow+3Zz61pZCqbBmAKuPhR+o/oU7NcoUABghU373EBRRue7tjUGywRtTq6bM84hCTKSwCb6fty7U7TTpw1Ee2zn25p5Ej0tmDM=";


        public string GenerateSignature<T>(T model) where T : class, new()
        {
            try
            {
                // 将模型转换为 JObject
                JObject jObject = JObject.FromObject(model);

                // 创建一个有序字典来存储参数
                var sortedParams = new SortedDictionary<string, string>();

                // 遍历 JObject，将非空值添加到有序字典
                foreach (var property in jObject.Properties())
                {
                    if (property.Value != null && property.Value.Type != JTokenType.Null)
                    {
                        sortedParams[property.Name] = property.Value.ToString();
                    }
                }

                // 组装待签名字符串
                string signContent = string.Join("&", sortedParams.Select(p => $"{p.Key}={p.Value}"));
                Console.WriteLine($"signContent:{signContent}");

                // RSA签名
                byte[] privateKeyBytes = Convert.FromBase64String(privateKey);
                RsaPrivateCrtKeyParameters privateKeyParams = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privateKeyBytes);

                using (var rsa = new RSACryptoServiceProvider())
                {
                    RSAParameters rsaParams = DotNetUtilities.ToRSAParameters(privateKeyParams);
                    rsa.ImportParameters(rsaParams);

                    byte[] dataToSign = Encoding.UTF8.GetBytes(signContent);
                    byte[] signatureBytes = rsa.SignData(dataToSign, new SHA256CryptoServiceProvider());
                    return Convert.ToBase64String(signatureBytes);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("签名过程中发生错误", ex);
            }
        }

        public string Post<T>(T model,string methon) where T : class, new() 
        {
            try
            {
                var client = new RestClient (url)
                {
                    Timeout = 10000,
                    Encoding = Encoding.UTF8,
                    ReadWriteTimeout = 10000,

                };
                var request = new RestRequest("", Method.POST);
                request.AlwaysMultipartFormData = true;
                request.AddParameter("version", "1.0");
                request.AddParameter("appid", appid);
                request.AddParameter("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                request.AddParameter("biz_content", Newtonsoft.Json.JsonConvert.SerializeObject(model,new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
                request.AddParameter("method", methon);// "park.record");
                var sign = GenerateSignature(model);
                request.AddParameter("sign", sign);
                var response = client.Execute(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                   return response.Content;// Newtonsoft.Json.JsonConvert.DeserializeObject<ApiRespons>(response.Content);
                }
            }
            catch (Exception ex)
            {
                return null;
            }

            return null;
        }
     }
}
